package com.osi.mes.qm.services;

import java.util.HashMap;
import java.util.Vector;

import pnuts.lang.Context;

import com.datasweep.compatibility.client.ATRow;
import com.datasweep.compatibility.client.ATRowFilter;
import com.datasweep.compatibility.client.DatasweepException;
import com.datasweep.compatibility.client.DependentATRow;
import com.datasweep.compatibility.client.OrderFilter;
import com.datasweep.compatibility.client.OrderItemFilter;
import com.datasweep.compatibility.client.ParentATRow;
import com.datasweep.compatibility.client.Report;
import com.datasweep.compatibility.client.Response;
import com.datasweep.compatibility.manager.ServerImpl;
import com.datasweep.compatibility.ui.Time;
import com.datasweep.plantops.common.constants.filtering.IFilterComparisonOperators;
import com.datasweep.plantops.common.constants.filtering.IWorkOrderFilterAttributes;
import com.datasweep.plantops.common.constants.filtering.IWorkOrderItemFilterAttributes;
import com.osi.mes.base.BaseService;
import com.osi.mes.qm.base.constants.IBasicConstants;
import com.osi.mes.utils.StringUtils;
import com.rockwell.operationalreporting.ReportDataSet;

public class QmShipReportService extends BaseService{

	public QmShipReportService(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	
	//按天查询工单
	public Vector<?> getWorkOrdersByTime(Time stTime,Time endTime)throws DatasweepException
	{
		Vector<?> vec = new Vector();
		OrderFilter orderFilter = getFunctions().createWorkOrderFilter();
		ServerImpl serverImpl = getFunctions().getCurrentUser().getServerImpl();
		OrderItemFilter orderItemFilter = new OrderItemFilter(serverImpl);
		orderFilter.addSearchForSubFilter(
			IWorkOrderFilterAttributes.KEY, IFilterComparisonOperators.IN,
			IWorkOrderItemFilterAttributes.ORDER_KEY, orderItemFilter);
		if(stTime!=null)
		{
			orderItemFilter.addSearchBy(IWorkOrderItemFilterAttributes.PLANNED_START_TIME,IFilterComparisonOperators.GREATER_THAN_EQUAL_TO,getDayStart(stTime));
		}
		
		if(endTime!=null)
		{
			orderItemFilter.addSearchBy(IWorkOrderItemFilterAttributes.PLANNED_START_TIME,IFilterComparisonOperators.LESS_THAN_EQUAL_TO,getDayEnd(endTime));
		}
		return  orderFilter.exec();
	}
	
	//查询当天的工单
	public Vector getTodayWorkOrders() throws DatasweepException
	{
		Time now = super.getTrxTime();
		return getWorkOrdersByTime(now,now);
	}
	
	//根据工单创建出厂报告
	public ATRow getShipReportByOrder(String orderNum) throws DatasweepException
	{
		if(StringUtils.isNull(orderNum))
			return null;
		
		ATRowFilter atFilter = getFunctions().createATRowFilter("QMProdShipOutReport");
		atFilter.forColumnNameEqualTo("order_num", orderNum);
		Vector<ATRow> vects = super.getATRows(atFilter);
		
		if(vects!=null && vects.size()>0)
			return  vects.get(0);
		
		return null;
	}
	
	//查询出厂报告
	public Vector<ATRow> searchShipReport(Time stTime,Time endTime,String orderNum)throws DatasweepException
	{
		ATRowFilter atFilter = getFunctions().createATRowFilter("QMProdShipOutReport");
		if(StringUtils.isNotNull(orderNum))
			atFilter.forColumnNameEqualTo("order_num", orderNum);
		if(stTime!=null)
		{
			atFilter.forColumnNameGreaterThan("create_time",getDayStart(stTime) );
		}
		
		if(endTime!=null)
		{
			atFilter.forColumnNameLessThan("create_time", getDayEnd(endTime));
		}
		
		Vector<ATRow> vects = super.getATRows(atFilter);
		return vects;
	}
	
	private String  getLotNos(ATRow shipReport)
	{
		String lots = "";
		if(shipReport instanceof ParentATRow)
		{
			ParentATRow pATRow = (ParentATRow)shipReport;
			Vector<DependentATRow> deptATRows = pATRow.getDependentATRows();
			
			for(int i=0;i<deptATRows.size();i++)
			{
				lots = lots + deptATRows.get(i).getValue("lot_num");
				if(i<deptATRows.size()-1)
					lots = lots +",";
			}
		}
		return lots;
	}
	
	public String getChkResult(Object result)
	{
		if(result instanceof Long)
		{
			int res = ((Long)result).intValue();
			if(res==0)
				return IBasicConstants.CHK_RESULT_OK;
			else if(res == 1)
				return IBasicConstants.CHK_RESULT_NOT_APP;
			else if(res == 2)
				return IBasicConstants.CHK_RESULT_NOT;
		}
		
		return "";
	}
	
	public String getRadioResult(Object result)
	{
		if(result instanceof Boolean)
		{
			boolean isOk = ((Boolean)result).booleanValue();
			if(isOk)
				return IBasicConstants.CHK_RESULT_YES;
			else
				return IBasicConstants.CHK_RESULT_NO;
		}
		return "";
	}
	
	private String getMicSt(ATRow shipReport)
	{
		String str = "";
		Boolean needColo = (Boolean)shipReport.getValue("microbe_need_colonies_st");
		if(needColo == true)
		{
			str = str + "菌落总数(cfu/g)：" +shipReport.getValue("microbe_colo_val_st");
		}
		
		Boolean needColi = (Boolean)shipReport.getValue("microbe_need_coli_st");
		if(needColi==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "大肠菌群(cfu/g)："+shipReport.getValue("microbe_coli_val_st");
		}
		
		Boolean needOther = (Boolean)shipReport.getValue("microbe_other_st");
		if(needOther==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "其他："+shipReport.getValue("microbe_other_val_st");
		}
		return str;
	}
	
	private String getMicChk(ATRow shipReport)
	{
		String str = "";
		Boolean needColo = (Boolean)shipReport.getValue("microbe_need_colonies_st");
		if(needColo == true)
		{
			str = str + "菌落总数(cfu/g)：" +shipReport.getValue("microbe_colo_val_act");
		}
		
		Boolean needColi = (Boolean)shipReport.getValue("microbe_need_coli_st");
		if(needColi==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "大肠菌群(cfu/g)："+shipReport.getValue("mic_coli_val_act");
		}
		
		Boolean needOther = (Boolean)shipReport.getValue("microbe_other_st");
		if(needOther==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "其他："+shipReport.getValue("mic_other_val_act");
		}
		return str;
	}
	
	private String getPhyCheSt(ATRow shipReport)
	{
		String str = "";
		Boolean needPer = (Boolean)shipReport.getValue("pc_need_per_st");
		if(needPer == true)
		{
			str = str + "过氧化值(g/100g):<=25%";
		}
		
		Boolean needSalt = (Boolean)shipReport.getValue("pc_need_salt_st");
		if(needSalt==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "盐份："+shipReport.getValue("pc_salt_val_st");
		}
		
		Boolean needWater = (Boolean)shipReport.getValue("pc_need_water_st");
		if(needWater==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "水份："+shipReport.getValue("pc_water_val_st");
		}
		
		Boolean needOther = (Boolean)shipReport.getValue("pc_need_other_st");
		if(needOther==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "其他："+shipReport.getValue("pc_other_val_st");
		}
		
		return str;
	}
	
	private String getPhyCheChk(ATRow shipReport)
	{
		String str = "";
		Boolean needPer = (Boolean)shipReport.getValue("pc_need_per_st");
		if(needPer == true)
		{
			str = str +"过氧化值(g/100g): "+ shipReport.getValue("pc_per_val_act");
		}
		
		Boolean needSalt = (Boolean)shipReport.getValue("pc_need_salt_st");
		if(needSalt==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "盐份："+shipReport.getValue("pc_salt_val_act");
		}
		
		Boolean needWater = (Boolean)shipReport.getValue("pc_need_water_st");
		if(needWater==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "水份："+shipReport.getValue("pc_water_val_act");
		}
		
		Boolean needOther = (Boolean)shipReport.getValue("pc_need_other_st");
		if(needOther==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "其他："+shipReport.getValue("pc_other_val_act");
		}
		
		return str;
	}
	
	private String getOtherSt(ATRow shipReport)
	{
		String str = "";
		Boolean needTw = (Boolean)shipReport.getValue("other_need_tw_st");
		if(needTw == true)
		{
			str = str +"解冻失水率: "+ shipReport.getValue("other_tw_val_st");
		}
		
		Boolean needOtherSt = (Boolean)shipReport.getValue("other_need_other_st");
		if(needOtherSt==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str + "其它："+shipReport.getValue("other_other_val_st");
		}
		
		return str;
	}
	
	private String getOtherChk(ATRow shipReport)
	{
		String str = "";
		Boolean needTw = (Boolean)shipReport.getValue("other_need_tw_st");
		if(needTw == true)
		{
			str = str +"解冻失水率: "+ shipReport.getValue("other_tw_val_act");
		}
		
		Boolean needOtherSt = (Boolean)shipReport.getValue("other_need_other_st");
		if(needOtherSt==true)
		{
			if(StringUtils.isNotNull(str))
				str = str +"\n";
			str = str +shipReport.getValue("other_other_val_act");
		}
		
		return str;
	}
	
	public Object replaceNull(Object res)
	{
		if(res == null)
			return "NA";
		
		return res;
	}
	
	
	//出厂报告打印
	public boolean printReport(ATRow shipReport,String filePath) throws Exception
	{
		try
		{
			Report report = getFunctions().createReport("osi_base_QMProdShipReport", "1");
			
			ReportDataSet rptSet = getFunctions().createReportDataSet();
			rptSet.setGlobalVariable("USER", replaceNull(getFunctions().getCurrentUser()));
			
		    HashMap<String,Object> rowMap = rptSet.createRow();
		    rowMap.put("prod_name", replaceNull(shipReport.getValue("prod_name")));
		    rowMap.put("produce_time", replaceNull(shipReport.getValue("produce_time")));
		    
		    rowMap.put("lot_no", getLotNos(shipReport));
		    
		    Long prodType = (Long)shipReport.getValue("prod_type");
		    if(prodType == 0)
		    {
		    	rowMap.put("prod_type","裹面制品" );
		    }
		    else if(prodType == 1)
		    	rowMap.put("prod_type","肉糜制品" );
		    else if(prodType == 2)
		    	rowMap.put("prod_type", "菜肴制品");
		    	
		    rowMap.put("prod_qty", replaceNull(shipReport.getValue("prod_qty")));
		    rowMap.put("prod_qua_no", replaceNull(shipReport.getValue("prod_qua_no")));
		    rowMap.put("prod_exe_st", replaceNull(shipReport.getValue("prod_exe_st")));
		    
		    Boolean needHeat = (Boolean)shipReport.getValue("prod_need_heat");
		    if(needHeat!=null && needHeat.booleanValue() == true)
		    {
		    	  rowMap.put("prod_category", "生制品");
		    }
		    else
		    {
		    	 rowMap.put("prod_category", "制热制品");
		    }
		  
		    rowMap.put("each_box_qty_st", replaceNull(shipReport.getValue("each_box_qty")));
		    rowMap.put("each_box_qty_chk", replaceNull(shipReport.getValue("each_box_qty_aver")));
		    rowMap.put("prod_spec_res", getChkResult(shipReport.getValue("each_box_qty_qua")));
		    rowMap.put("shelf_time_st", replaceNull(shipReport.getValue("prod_shelf_days_st")));
		    
		    Object prodProduceTimeAct = shipReport.getValue("prod_produce_time_ac");
		    if(prodProduceTimeAct!=null && prodProduceTimeAct instanceof Time)
		    {
		    	Time produceTimeAct = (Time)prodProduceTimeAct;
		    	rowMap.put("prod_produce_time_act",StringUtils.formatTime(produceTimeAct, "yyyy-MM-dd"));
		    }
		    else
		    	rowMap.put("prod_produce_time_act","NA");
		    
		    Object overTime = shipReport.getValue("prod_overTime_ac");
		    if(overTime!=null && overTime instanceof Time)
		    {
		    	 rowMap.put("prod_shelf_time_act", StringUtils.formatTime((Time)overTime, "yyyy-MM-dd"));
		    }
		    else
		    	rowMap.put("prod_shelf_time_act", "NA");
		    
		    rowMap.put("prod_pTime_correct", getRadioResult(shipReport.getValue("produce_time_correct")));
		    rowMap.put("prod_shelf_time_act",getRadioResult(shipReport.getValue("overTime_clear")));
		    
		    rowMap.put("sensory_form_ok", getRadioResult(shipReport.getValue("sensory_form_ok")));
		    rowMap.put("sensory_color_ok", getRadioResult(shipReport.getValue("sensory_color_ok")));
		    rowMap.put("sensory_org_ok", getRadioResult(shipReport.getValue("sensory_org_ok")));
		    rowMap.put("sensory_smell_ok", getRadioResult(shipReport.getValue("sensory_smell_ok")));
		    rowMap.put("sensory_no_fm", getRadioResult(shipReport.getValue("sensory_free_fm_ok")));
		    rowMap.put("sensory_ok",  getChkResult(shipReport.getValue("sensory_qua")));
		    
		    Object ccpMeatDec = shipReport.getValue("metal_detection");
		    if(ccpMeatDec!=null)
		    {
		    	if(ccpMeatDec instanceof Boolean)
		    	{
		    		boolean metalDec = ((Boolean)ccpMeatDec).booleanValue();
		    		if(metalDec)
		    			 rowMap.put("ccp_meat_dec", "正常");
		    		else
		    			rowMap.put("ccp_meat_dec", "不正常");
		    	}
		    }
		    
		    Object refinedOver = shipReport.getValue("refined_over");
		    if(refinedOver!=null)
		    {
		    	if(refinedOver instanceof Boolean)
		    	{
		    		boolean refOver = ((Boolean)refinedOver).booleanValue();
		    		if(refOver)
		    			 rowMap.put("ccp_refined_over", "正常");
		    		else
		    			rowMap.put("ccp_refined_over", "不正常");
		    	}
		    }
		    
		    rowMap.put("ccp_ok", getChkResult(shipReport.getValue("ccp_qua")));
		    rowMap.put("bbq_ass_score", replaceNull(shipReport.getValue("bbq_score")));
		    rowMap.put("each_bbq_than_sixty",  getRadioResult(shipReport.getValue("each_bbq_than_sixty")));
		    rowMap.put("bbq_ok", getChkResult(shipReport.getValue("bbq_qua")));
		    
		    rowMap.put("package_well", getRadioResult(shipReport.getValue("package_well")));
		    rowMap.put("package_ok", getRadioResult(shipReport.getValue("package_qua")));
		    
		    Boolean needMat = (Boolean)shipReport.getValue("main_need_batter_st");
			if(needMat == true)
			{
				rowMap.put("need_batter", "裹面制品：芯料>=50%");
			}
			else
				rowMap.put("need_batter", "NA");
			
			Boolean needMeat = (Boolean)shipReport.getValue("main_need_meat_st");
			if(needMeat==true)
			{
				 rowMap.put("need_meat", "肉糜类制品：鸡肉>=10%;牛肉>=8% ");
			}
			else
				rowMap.put("need_meat", "NA");
			
			Boolean needVeg = (Boolean)shipReport.getValue("main_need_vege_st");
			if(needVeg==true)
			{
				rowMap.put("need_veg", "菜肴制品：主料>=20%");
			}
			else
				rowMap.put("need_veg", "NA");
		   
		    rowMap.put("recipe_ok", getRadioResult(shipReport.getValue("main_recipe_ok")));
		    rowMap.put("main_ok", getChkResult(shipReport.getValue("main_qua")));
		    
		    rowMap.put("mic_st", getMicSt(shipReport));
		    rowMap.put("mic_act", getMicChk(shipReport));
		    rowMap.put("mic_ok", getChkResult(shipReport.getValue("mic_qua")));
		    
		    rowMap.put("pc_st", getPhyCheSt(shipReport));
		    rowMap.put("pc_act", getPhyCheChk(shipReport));
		    rowMap.put("pc_ok", getChkResult(shipReport.getValue("pc_qua")));
			
		    rowMap.put("other_st", getOtherSt(shipReport));
		    rowMap.put("other_act", getOtherChk(shipReport));
		    rowMap.put("other_ok",getChkResult(shipReport.getValue("other_qua")));
		    
		    Object auditState =shipReport.getValue("audit_state");
		    if(auditState!=null)
		    {
		    	Boolean auditS = (Boolean)auditState;
		    	if(auditS==true)
		    	{
		    		rowMap.put("audit_state", "合格");
		    	}
		    	else
		    	{
		    		rowMap.put("audit_state", "不合格");
		    	}
		    	rowMap.put("audit_user", shipReport.getValue("audit_user")); 
		    	Time auTime = (Time)shipReport.getValue("audit_time");
		    	rowMap.put("audit_time",StringUtils.formatTime(auTime, "yyyy-MM-dd") );
		    }
		    else
		    {
		    	rowMap.put("audit_state", "未审核");
		    	rowMap.put("audit_user", ""); 
		    	rowMap.put("audit_time","");
		    }
		    
		    rptSet.appendRow(rowMap);
		    report.setReportDataSet(rptSet);
		    Response response = report.generate();
		    
		    if(response.isError())
		    	throw new Exception(response.getFirstErrorMessage());
		   return  super.exportToExcel(filePath, report);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw e;
		}
		
	}
	
}
